<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable>
          <el-option
            v-for="project in projectList"
            :key="project.projectId"
            :label="project.projectName"
            :value="project.projectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable>
          <el-option
            v-for="user in userList"
            :key="user.userId"
            :label="user.nickName"
            :value="user.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="queryParams.role" placeholder="请选择角色" clearable>
          <el-option
            v-for="dict in pm_member_role"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择状态" clearable>
          <el-option label="活跃" :value="true" />
          <el-option label="非活跃" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pm:project:member:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pm:project:member:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:project:member:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pm:project:member:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="用户昵称" align="center" prop="nickName">
        <template #default="scope">
          <span v-if="scope.row.nickName">{{ scope.row.nickName }}</span>
          <span v-else-if="scope.row.userId">{{ getUserNickNames(scope.row.userId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" prop="userName">
        <template #default="scope">
          <span v-if="scope.row.userName">{{ scope.row.userName }}</span>
          <span v-else-if="scope.row.userId">{{ getUserNames(scope.row.userId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center" prop="role">
        <template #default="scope">
          <dict-tag 
            :options="pm_member_role || []" 
            :value="scope.row.role"
            v-if="pm_member_role && pm_member_role.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.role || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="加入日期" align="center" prop="joinDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.joinDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="isActive">
        <template #default="scope">
          <el-tag :type="scope.row.isActive === true ? 'success' : 'info'">
            {{ scope.row.isActive === true ? '活跃' : '非活跃' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['pm:project:member:query']"
          >查看</el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:project:member:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:project:member:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目成员对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目" :disabled="isView">
            <el-option
              v-for="project in projectList"
              :key="project.projectId"
              :label="project.projectName"
              :value="project.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户" prop="userIds">
          <el-select 
            v-model="form.userIds" 
            placeholder="请选择用户（可多选）" 
            clearable 
            multiple
            filterable
            :loading="userLoading"
            @focus="loadUsers"
            :disabled="isView"
          >
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            >
              <span style="float: left">{{ user.nickName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ user.userName }}</span>
            </el-option>
          </el-select>
          <div class="el-form-item__help" style="color: #909399; font-size: 12px; margin-top: 4px;">
            支持多选，一次可以添加多个成员到项目中
          </div>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色" :disabled="isView">
            <el-option
              v-for="dict in pm_member_role"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="加入日期" prop="joinDate">
          <el-date-picker
            v-model="form.joinDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择加入日期"
            :disabled="isView"
          />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-radio-group v-model="form.isActive" :disabled="isView">
            <el-radio :label="true">活跃</el-radio>
            <el-radio :label="false">非活跃</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="isView" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel" v-if="!isView">取 消</el-button>
          <el-button type="primary" @click="submitForm" v-if="!isView">确 定</el-button>
          <el-button @click="cancel" v-if="isView">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PmProjectMember" lang="ts">
import { listProjectMember, getProjectMember, delProjectMember, addProjectMember, updateProjectMember } from '@/api/pm/project-member'
import { listProject } from '@/api/pm/project'
import { listUser } from '@/api/system/user'
import { ref, reactive, onMounted, getCurrentInstance, toRefs } from 'vue'
import type { ElFormInstance } from 'element-plus'

// 获取当前实例
const { proxy } = getCurrentInstance() as any

// 获取字典数据 - 使用 proxy.useDict 方式
const { pm_member_role } = toRefs<any>(proxy?.useDict('pm_member_role'))

// 调试：打印字典数据
console.log('pm_member_role 字典数据:', pm_member_role.value)


const memberList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const isView = ref(false)
const projectList = ref([])
const userList = ref([])
const userLoading = ref(false)

// 表单引用
const formRef = ref<ElFormInstance>()

const data = reactive({
  form: {
    userIds: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: null,
    userId: null,
    role: null,
    isActive: null
  },
  rules: {
    projectId: [
      { required: true, message: '项目不能为空', trigger: 'change' }
    ],
    userIds: [
      { required: true, message: '请至少选择一个用户', trigger: 'change' }
    ],
    role: [
      { required: true, message: '角色不能为空', trigger: 'change' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询项目成员列表 */
function getList() {
  loading.value = true
  listProjectMember(queryParams.value).then(response => {
    memberList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 获取用户名称（处理多用户ID） */
const getUserNames = (userIdStr: string) => {
  if (!userIdStr) return '';
  console.log('getUserNames - userIdStr:', userIdStr);
  console.log('getUserNames - userList:', userList.value);
  
  // 保持字符串格式，避免大整数精度丢失
  const userIds = userIdStr.split(',').map(id => id.trim());
  console.log('getUserNames - userIds (字符串):', userIds);
  
  const names = userIds.map(id => {
    // 尝试多种匹配方式
    let user = userList.value.find(u => u.userId == id); // 使用 == 进行宽松比较
    if (!user) {
      user = userList.value.find(u => u.userId === String(id));
    }
    if (!user) {
      user = userList.value.find(u => String(u.userId) === String(id));
    }
    if (!user) {
      // 尝试Number匹配
      user = userList.value.find(u => Number(u.userId) === Number(id));
    }
    if (!user) {
      // 尝试BigInt匹配（处理大整数）
      try {
        user = userList.value.find(u => u.userId === BigInt(id));
      } catch (e) {
        // BigInt转换失败，忽略
      }
    }
    console.log(`getUserNames - 查找用户ID "${id}" (类型: ${typeof id}):`, user);
    return user ? user.userName : `用户${id}`;
  });
  console.log('getUserNames - names:', names);
  return names.join(', ');
}

/** 获取用户昵称（处理多用户ID） */
const getUserNickNames = (userIdStr: string) => {
  if (!userIdStr) return '';
  console.log('getUserNickNames - userIdStr:', userIdStr);
  console.log('getUserNickNames - userList:', userList.value);
  
  // 保持字符串格式，避免大整数精度丢失
  const userIds = userIdStr.split(',').map(id => id.trim());
  console.log('getUserNickNames - userIds (字符串):', userIds);
  
  // 打印用户列表中所有用户的ID，帮助调试
  console.log('用户列表中的所有用户ID:', userList.value.map(u => ({ userId: u.userId, nickName: u.nickName })));
  
  const names = userIds.map(id => {
    // 尝试多种匹配方式
    let user = userList.value.find(u => u.userId == id); // 使用 == 进行宽松比较
    if (!user) {
      user = userList.value.find(u => u.userId === String(id));
    }
    if (!user) {
      user = userList.value.find(u => String(u.userId) === String(id));
    }
    if (!user) {
      // 尝试Number匹配
      user = userList.value.find(u => Number(u.userId) === Number(id));
    }
    if (!user) {
      // 尝试BigInt匹配（处理大整数）
      try {
        user = userList.value.find(u => u.userId === BigInt(id));
      } catch (e) {
        // BigInt转换失败，忽略
      }
    }
    console.log(`getUserNickNames - 查找用户ID "${id}" (类型: ${typeof id}):`, user);
    return user ? user.nickName : `用户${id}`;
  });
  console.log('getUserNickNames - names:', names);
  return names.join(', ');
}

/** 懒加载用户列表 */
const loadUsers = () => {
  if (userList.value.length > 0) return; // 避免重复加载
  userLoading.value = true;
  listUser({ pageNum: 1, pageSize: 1000 }).then(response => {
    userList.value = response.rows || [];
    userLoading.value = false;
  }).catch(error => {
    console.error('获取用户列表失败:', error);
    userList.value = [];
    userLoading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: null,
    userId: null,
    role: null,
    joinDate: null,
    isActive: true,
    remark: null
  }
  isView.value = false
  proxy?.$nextTick(() => {
    formRef.value?.resetFields();
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy?.resetForm('queryForm')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加项目成员'
  isView.value = false
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const memberId = row.id || ids.value
  getProjectMember(memberId).then(response => {
    const memberData = response.data;
    console.log('修改时获取的项目成员数据:', memberData);
    
    // 将用户ID字符串转换为数组格式，用于多选组件
    let userIds = [];
    if (memberData.userId) {
      // 先尝试转换为数字，如果失败则保持字符串
      userIds = memberData.userId.split(',').map(id => {
        const trimmedId = id.trim();
        const numId = parseInt(trimmedId);
        // 检查转换后的数字是否与原字符串相等，避免精度丢失
        if (String(numId) === trimmedId) {
          return numId;
        } else {
          return trimmedId; // 保持字符串格式
        }
      });
    }
    
    console.log('解析后的userIds:', userIds);
    console.log('用户列表中的userId类型:', userList.value.length > 0 ? typeof userList.value[0].userId : 'unknown');
    
    form.value = {
      ...memberData,
      userIds: userIds
    };
    open.value = true
    title.value = '修改项目成员'
    isView.value = false
  })
}

/** 查看按钮操作 */
function handleView(row) {
  reset()
  const memberId = row.id || ids.value
  getProjectMember(memberId).then(response => {
    const memberData = response.data;
    console.log('查看时获取的项目成员数据:', memberData);
    
    // 将用户ID字符串转换为数组格式，用于多选组件显示
    let userIds = [];
    if (memberData.userId) {
      // 先尝试转换为数字，如果失败则保持字符串
      userIds = memberData.userId.split(',').map(id => {
        const trimmedId = id.trim();
        const numId = parseInt(trimmedId);
        // 检查转换后的数字是否与原字符串相等，避免精度丢失
        if (String(numId) === trimmedId) {
          return numId;
        } else {
          return trimmedId; // 保持字符串格式
        }
      });
    }
    
    console.log('查看时解析后的userIds:', userIds);
    
    form.value = {
      ...memberData,
      userIds: userIds
    };
    open.value = true
    title.value = '查看项目成员'
    isView.value = true
  })
}

/** 提交按钮 */
function submitForm() {
  formRef.value?.validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProjectMember(form.value).then(response => {
          proxy?.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addProjectMember(form.value).then(response => {
          proxy?.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const memberIds = row.id || ids.value
  proxy?.$modal.confirm('是否确认删除项目成员编号为"' + memberIds + '"的数据项？').then(function() {
    return delProjectMember(memberIds)
  }).then(() => {
    getList()
    proxy?.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('pm/project/member/export', {
    ...queryParams.value
  }, `project_member_${new Date().getTime()}.xlsx`)
}

/** 获取项目列表 */
function getProjectList() {
  return listProject().then(response => {
    projectList.value = response.rows
  })
}

/** 获取用户列表 */
function getUserList() {
  return listUser().then(response => {
    userList.value = response.rows
    console.log('项目成员页面用户列表加载完成:', userList.value);
    // 打印前几个用户的数据结构，帮助调试
    if (userList.value.length > 0) {
      console.log('第一个用户数据结构:', userList.value[0]);
      console.log('用户ID字段类型:', typeof userList.value[0].userId);
      console.log('用户ID字段值:', userList.value[0].userId);
    }
  })
}

onMounted(async () => {
  // 先加载基础数据，再加载列表
  await getProjectList()
  await getUserList()
  getList()
})
</script>
